class Solution
{
public:
    long long countFairPairs(vector<int> &nums, int lower, int upper)
    {
        sort(nums.begin(), nums.end());
        long long result = 0;
        int n = nums.size();
        for (int i = 0; i < n; ++i)
        {
            int l = lower_bound(nums.begin(), nums.end(), lower - nums[i]) - nums.begin();
            int r = upper_bound(nums.begin(), nums.end(), upper - nums[i]) - nums.begin();
            result += r - l;
            if (l <= i && r > i)
            {
                result -= 1;
            }
        }
        return result / 2;
    }
};